package com.seeyon.apps.kkSample.controller;

import com.seeyon.apps.kkSample.manager.KKEsignCallBackManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.logging.Log;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author: L
 * @Description:
 * @Date: 创建于10:18 2022-10-24
 **/
public class KKESignController extends BaseController {

    private static final Log LOG = CtpLogFactory.getLog(KKESignController.class);
    private KKEsignCallBackManager kkESignCallBackManager = (KKEsignCallBackManager) AppContext.getBean("kkESignCallBackManager");

    /**
     * e签宝回调方法
     *
     * @param request
     * @param response
     * @return
     */
    public ModelAndView callBack(HttpServletRequest request, HttpServletResponse response) {
        LOG.info("e签宝回调方法开始执行start");
        ModelAndView modelAndView = new ModelAndView("apps/kkEsign/retDone");
        //用来接收回调方法的请求体
        Map<String, Object> bodyMap;
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            String inputStr = "";

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            while ((inputStr = bufferedReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            bodyMap = JSONUtil.parseJSONString(responseStrBuilder.toString(), Map.class);
            LOG.info("接收回调方法请求体参数成功：" + bodyMap);
            //调用解析事件类型方法
            kkESignCallBackManager.action(bodyMap);
            modelAndView.addObject("code", "200");
            modelAndView.addObject("msg", "success");
        } catch (UnsupportedEncodingException e) {
            LOG.error("setCharacterEncoding(\"utf-8\")异常：;" + e.getMessage(), e);
        } catch (IOException e) {
            LOG.error("接收回调方法请求体参数异常：" + e.getMessage(), e);
        }
        LOG.info("e签宝回调方法执行结束end");
        return modelAndView;
    }
}
